<?php
	header ('Content-type: text/plain; charset=utf-8');

	//Load Database Class
	include('database.class.php');
	//set max_execution_time;
	//ini_set('max_execution_time', 0);	
	$db = new Database('10.10.2.161','you2play_ee','r7brUXHK4GRypdRb','you2play_2013');
	//Connect Database
	$db->connect();	
	$start = 1317;
	$limit = 10;
	$upload_path = '/home/you2play/engine/static/2013/assets/uploads/';
	$source_path = '/home/you2play/engine/static/files/video/dest/';
	//Set Limit Time
	set_time_limit(60*60*24);	
	//Start ob_start
	ob_start();
	//Loop Infinite
	while(true):
		if (!mysql_ping($db->link_id)) {
		   //here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
			//close Connection
			$db->close();
			usleep(3000000); //หยุดหายใจก่อน 3 วินาที		
			//call Database 
			$db = new Database('10.10.2.161','you2play_ee','r7brUXHK4GRypdRb','you2play_2013');
			$db->connect();	
		}
		$SQL = "SELECT t.movie_id,t.create_date,k.video_id,k.add_date FROM you2play_2013.oni_movie as t INNER JOIN you2play_ee.exp_video_posts as j ON(j.entry_id=t.movie_id) INNER JOIN you2play_ee.exp_video_files as k ON(k.video_id=j.video_id) ORDER BY movie_id ASC LIMIT ".$start.",".$limit."";
		$dataResult = $db->fetch_all_array($SQL);
		$start = $start + $limit; //Add by Limit
		if(empty($dataResult)):
			exit; //Exit
		endif;		
		foreach($dataResult as $value):
			$dateY = date('Y',strtotime($value['create_date'])).'/';
			$dateM = date('m',strtotime($value['create_date'])).'/';
			$dateD = date('d',strtotime($value['create_date'])).'/';
			$new_path = $upload_path.'movie/files/';	
			@mkdir($new_path.$dateY);
			@mkdir($new_path.$dateY.$dateM);
			@mkdir($new_path.$dateY.$dateM.$dateD);
			$new_path = $new_path.$dateY.$dateM.$dateD.$value['video_id'].'.mp4';
			$dateYold = date('Y',strtotime($value['add_date'])).'/';
			$dateMold = date('m',strtotime($value['add_date'])).'/';
			$dateDold = date('d',strtotime($value['add_date'])).'/';			
			$old_path = $source_path.$dateYold.$dateMold.$dateDold.$value['video_id'].'.mp4';
			@copy($old_path, $new_path);
			//Report
			echo "Complete ID:".$value['movie_id']." Filename:".$new_path."\r\n";	
			ob_flush();  
	    	flush(); 			
		endforeach;
	endwhile;
	//Close Database
	$db->close();
?>
